﻿using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using SuperSocket.ProtoBase;



namespace SuperWeight
{
    /// <summary>
    /// 接收到称重数据
    /// </summary>
    /// <param name="ActionName">触发动作名</param>
    /// <param name="ActionValue">触发动作内容</param>
    public delegate void Action_DataReceive(WeightPackageInfo Data);
    public class WeightHelper
    {
        /// <summary>
        /// TCP连接对象
        /// </summary>
        public EasyClient Weight = new EasyClient();
  

        /// <summary>
        /// 构造函数
        /// </summary>
        public WeightHelper()
        {
            //TCP连接对象初始化
            Weight.Initialize(new WeightReceiveFilter(), (Data) =>
            {
                if (Data != null)
                {
                    if (WeightReceive != null)
                    {
                        WeightReceive.BeginInvoke(Data, null, null);
                    }
                    //WeightReceive?.BeginInvoke(Data, null, null);
                }
            });
        }

        /// <summary>
        /// 开启连接
        /// </summary>
        /// <returns></returns>
        public bool Open(string IpAddress, int Port)
        {
            if (Weight.IsConnected)
            {
                return true;
            }
            return Weight.ConnectAsync(new IPEndPoint(IPAddress.Parse(IpAddress), Port)).Result;
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            if (!Weight.IsConnected)
            {
                return true;
            }
            return Weight.Close().Result;
        }

        /// <summary>
        /// 事件接收到数据
        /// </summary>
        /// <param name="Data"></param>
        public event Action_DataReceive WeightReceive;
    }
}
